import React, { useEffect, useState } from 'react'
import { Button, Modal, Form, Input, message } from 'antd'
import projectApi, { formDataModel, userItemsModel } from '@/api/project'
export default function Usermodel(props: any) {
  const [form] = Form.useForm()
  let { isShow, setIsShow, userData, reqUserList } = props
  const [formData, setFormData] = useState<userItemsModel>({ nickName: '', username: '' })
  const onSave = async () => {
    try {
      await form.validateFields()
      await projectApi.AEUser(formData)
      message.success('保存成功')
      reqUserList()
      setIsShow(false)
    } catch (error) {
      message.error(error)
    } finally {
    }
  }
  useEffect(() => {
    setFormData({ ...userData })
    form.setFieldsValue({ userName: userData?.username })
  }, [userData])
  return (
    <>
      <Modal
        forceRender={true}
        destroyOnClose={true}
        title={formData.id?"修改用户":"添加用户"}
        open={isShow}
        onOk={onSave}
        onCancel={() => setIsShow(false)}
      >
        <Form name="basic" form={form} labelCol={{ span: 5 }} initialValues={{ userName: formData.username }}>
          <Form.Item
            name="userName"
            label="用户名"
            validateTrigger={'onBlur'}
            rules={[
              {
                validator(rule, value) {
                  if (!value) {
                    return Promise.reject('用户名不能为空')
                  }
                  if (value.length < 5) {
                    return Promise.reject('用户名称不能少于4个字')
                  }
                  return Promise.resolve()
                }
              }
            ]}
          >
            <Input
              value={formData.username}
              onInput={(e) => setFormData({ ...formData, username: (e.target as any).value })}
            />
          </Form.Item>
          <Form.Item label="用户昵称">
            <Input
              value={formData.nickName}
              onInput={(e) => setFormData({ ...formData, nickName: (e.target as any).value })}
            />
          </Form.Item>
          {!formData.id && (
            <Form.Item
              label="用户密码"
              name="password"
              validateTrigger={'onBlur'}
              rules={[
                {
                  validator(rule, value) {
                    if (!value) {
                      return Promise.reject('密码不能为空')
                    }
                    if (value.length < 5) {
                      return Promise.reject('密码不能少于6个字')
                    }
                    return Promise.resolve()
                  }
                }
              ]}
            >
              <Input
                value={formData.password}
                onInput={(e) => setFormData({ ...formData, password: (e.target as any).value })}
              />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </>
  )
}
